/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Date: 2025-06-24
 * Time: 23:01
 */
class ListNode {
      int val;
      ListNode next;
      ListNode(int x) {
          val = x;
          next = null;
      }

    @Override
    public String toString() {
        return ""+val;
    }
}
public class Test {
    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null||headB==null){
            return null;
        }
        int a=0;
        int b=0;
        ListNode P1=headA;
        ListNode P2=headB;
        while(P1!=null){
            a++;
            P1=P1.next;
        }
        while(P2!=null){
            b++;
            P2=P2.next;
        }
        if(a>=b){
            int n=a-b;
            while(n-->0){
                headA=headA.next;
            }
        }
        else{
            int n=b-a;
            while(n-->0){
                headB=headB.next;
            }
        }
        while(headA!=null){
            if(headA==headB){
                return headA;
            }
            headA=headA.next;
            headB=headB.next;
        }
        return null;
    }

    public static void main(String[] args) {
        ListNode list1=new ListNode(1);
        ListNode list2=new ListNode(2);
        ListNode list3=new ListNode(3);
        ListNode list4=new ListNode(4);
        ListNode list5=new ListNode(5);
        list1.next=list2;
        list2.next=list3;
        list3.next=list4;
        list5.next=list3;
        System.out.println(getIntersectionNode(list1,list5));
    }

}
